package com.wind.plugin.common;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vcs.VcsDirectoryMapping;
import com.intellij.psi.PsiElement;
import com.intellij.psi.xml.XmlTag;
import com.wind.plugin.config.CurrencySettings;
import com.wind.plugin.configuration.PluginSettingsState;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Common {
    // 获取当前项目Git 仓库路径
    public static String getGitRepositoryPath(Project project) {
        ProjectLevelVcsManager vcsManager = ProjectLevelVcsManager.getInstance(project);
        List<VcsDirectoryMapping> rootDirs = vcsManager.getDirectoryMappings(); // 获取all版本控制根目录mapping
        String gitResPath = "";
        for (VcsDirectoryMapping mapping : rootDirs) {
            if ("Git".equals(mapping.getVcs())) {
                // 构造 Git 仓库路径
                gitResPath =  mapping.getDirectory();
            }
        }

        return "".equals(gitResPath)?project.getBasePath():gitResPath;
    }

    // 判断指定行的提交信息日期是否晚于指定日期
    public static boolean isCommitAfterDate(String gitRepoPath, String filePath, int lineNum, LocalDate compareDate) {
        String gitCommand = "git blame -L " + lineNum + "," + lineNum + " " + filePath;
        try {

            ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c",gitCommand);
            processBuilder.directory(new File(gitRepoPath));
            Process process = processBuilder.start();

            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    LocalDate commitDate = extractCommitDate(line);
                    if (commitDate != null && commitDate.isAfter(compareDate)) {
                        return true;
                    }
                    break; // 只需要检查第一个匹配的提交信息即可
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
        return false;
    }

    // 从提交信息中提取日期
    public static LocalDate extractCommitDate(String commitInfo) {
        Pattern pattern = Pattern.compile("\\d{4}-\\d{2}-\\d{2}");
        Matcher matcher = pattern.matcher(commitInfo);
        if (matcher.find()) {
            String dateString = matcher.group(0);
            return LocalDate.parse(dateString, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }
        return null;
    }

    public static boolean shouldSkipCheck(XmlTag tag) {
        // 查找前一个有效的兄弟元素（跳过空白和空行）
        PsiElement prevSibling = findPreviousValidSibling(tag);

        // 如果找到的元素是注释，并且包含特定的关键字
        if (prevSibling != null && isComment(prevSibling)) {
            String commentText = prevSibling.getText().trim();
            return containsSkipKeyword(commentText);
        }

        // 如果不满足条件，返回 false
        return false;
    }

    /**
     * 查找前一个有效的兄弟元素，跳过空白和空行
     */
    private static PsiElement findPreviousValidSibling(XmlTag tag) {
        PsiElement prevSibling = tag.getPrevSibling();

        // 循环向上查找，直到找到一个非空的兄弟元素
        while (prevSibling != null && prevSibling.getText().trim().isEmpty()) {
            prevSibling = prevSibling.getPrevSibling();
        }

        return prevSibling;
    }

    /**
     * 判断该元素是否是注释类型
     */
    private static boolean isComment(PsiElement element) {
        return element.getText().trim().startsWith("<!--");
    }

    /**
     * 判断注释内容是否包含跳过检查的关键字
     */
    private static boolean containsSkipKeyword(String commentText) {
        return commentText.contains("skipCheck imCustNo");
    }

    public static Pattern getCurPattern() {
        // 获取当前的配置
        List<String> currencyKeywords = PluginSettingsState.getInstance().getCurrencyFields();

        // 使用正则表达式匹配
        StringBuilder patternBuilder = new StringBuilder("\\b(");
        for (String keyword : currencyKeywords) {
            if (patternBuilder.length() > 4) {
                patternBuilder.append("|");
            }
            patternBuilder.append(keyword);
        }
        patternBuilder.append(")\\b");

        return Pattern.compile(patternBuilder.toString(), Pattern.CASE_INSENSITIVE);
    }
}
